import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { decodeAES } from '@/utils/aesRsa'
import { isArray } from '@/utils/is'

const { t } = useI18n() // 国际化

/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkPermit(value: string[]) {
  if (value && value instanceof Array && value.length > 0) {
    const { wsLocal } = useCache()
    const permissionData = value
    const all_permission = '*:*:*'
    const permissions = decodeAES(wsLocal.getItem(CACHE_KEY.USER_INFO)).permit
    const hasPermission = permissions.some(permission => {
      return all_permission === permission || permissionData.includes(permission)
    })
    return !!hasPermission
  } else {
    console.error(t('permit', 'hasPermit'))
    return false
  }
}

// 计算操作栏宽度
export const computedOperateWidth = (value: any) => {
  let operateWidth = 26
  value.forEach(item => {
    if (isArray(item)) {
      if (checkPermit(item)) {
        operateWidth += 56
      }
    } else {
      if (checkPermit([item])) {
        if (item.includes(':update-master')) {
          operateWidth += 74
        } else if (item.includes(':test')) {
          operateWidth += 80
        } else if (item.includes(':create') || item.includes(':update') || item.includes(':delete') || item.includes(':push')) {
          operateWidth += 56
        } else if (item.includes(':index')) {
          operateWidth += 80
        } else if (item.includes(':assign-role-data-scope') || item.includes(':assign-role-menu')) {
          operateWidth += 74
        }
      }
    }
  })
  return operateWidth
}

/**
 * 角色权限校验
 * @param {string[]} value 校验值
 * @returns {Boolean}
 */
export function checkRole(value: string[]) {
  if (value && value instanceof Array && value.length > 0) {
    const { wsLocal } = useCache()
    const permissionRoles = value
    const super_admin = 'admin'
    const roles = decodeAES(wsLocal.getItem(CACHE_KEY.USER_INFO)).roles
    const hasRole = roles.some(role => {
      return super_admin === role || permissionRoles.includes(role)
    })
    return !!hasRole
  } else {
    console.error(t('permit', 'hasRole'))
    return false
  }
}
